<?php

/**
 * User: CQH
 * Date: 2017/8/28
 * Time: 09:48
 */

namespace app\common\model;

use think\Loader;
use think\Model;
use think\db;
use app\common\model\Customer;
use app\common\model\RepairRecord;

/*
 * 合同信息model---废弃
 */

class Contract extends Model {

    protected $db;
    protected $contract_equipment;
    protected $db_name = "admin_user";
    protected $db_name_log = 'admin_log';

    public function __construct($table_name = '', $table_log = '') {
        //日志表
        if (!empty($table_name)) {
            $this->db_name = $table_name;
        }
        if (!empty($table_log)) {
            $this->db_name_log = $table_log;
        }
        parent::__construct();
        $this->db = Db::name("Contract");
        $this->contract_equipment = Db::name("contract_equipment");
    }

    /**
     * 合同记录增加一条数据
     * @param $data  ->  数组   ['key' => 'value']
     * @return bool
     */
    public function insertOne($data) {
        //$this->data($data);
        $result = $this->db->insertGetId($data);

        return $result;
    }

    /**
     * --------------------------
     * edit:增加写入日志操作
     * author:ligang
     * time：2017年8月29日14:48:16
     * --------------------------
     * 按contract_id主键删除一条数据（逻辑删除）
     * @param $id
     * @return array|bool
     */
    public function deleteOne($id) {
        $result = $this->db->where(array('contract_id' => $id))->setField('is_delete', 1);
        if ($result !== 1) {
            writelog($this->user_data['uid'], $this->user_data['username'], '用户【' . $this->user_data['username'] . '】删除失败：合同ID：' . $id, 0, $this->db_name_log);
            return false;
        }
        writelog($this->user_data['uid'], $this->user_data['username'], '用户【' . $this->user_data['username'] . '】删除成功：合同ID：' . $id, 1, $this->db_name_log);
        return $result;
    }

    /**
     * 根据条件 $where修改一条数据
     * @param $where ->  条件  ['key' => 'value']
     * @param $data  ->  数据  ['key' => 'value', 'key' => 'value']
     * @return int|bool
     */
    public function updateOne($where, $data) {
        // 根据条件修改一条数据
        $result = $this->db->where($where)->update($data);
        // 判断结果 并返回数据
        if ($result == false) {
            return false;
        }
        return $result;
    }

    /**
     * 根据条件 $where获取单条数据
     * @param $where  ->  数组  ['key' => 'value']
     * @return bool|false|\PDOStatement|string|\think\Collection    
     */
    public function selectOne($where) {
        $userInfo = $this->db->where($where)->cache(true)->select();
        // 判断结果并返回
        if ($userInfo == false) {
            return false;
        }
        return $userInfo;
    }

    /**
     * 获取所有 未被逻辑删除的数据
     * @return bool|false|\PDOStatement|string|\think\Collection    
     */
    public function getList() {
        $userInfo = $this->db->where(array('is_delete' => 0))->cache(true)->select();
        // 判断结果 并返回
        if ($userInfo == false) {
            return false;
        }
        return $userInfo;
    }

    /**
     * 获取所有数据 (包含被逻辑删除的数据)
     * @return bool|false|\PDOStatement|string|\think\Collection
     */
    public function getListAll() {
        $userInfo = $this->db->cache(true)->select();
        // 判断结果 并返回
        if ($userInfo == false) {
            return false;
        }
        return $userInfo;
    }

    /**
     * --------------------------------
     * 增加合同相关操作
     * @author ligang
     * @time 2017年8月28日11:28:52
     * --------------------------------
     */

    /**
     * 添加合同(并返回ID)
     * @author ligang
     * @param array     $data                       数据
     * @return int
     */
    public function insertContract($data) {
        $result = $this->db->insertGetId($data);
        return $result;
    }

    /*
     * 批量添加合同
     * @author ligang
     * @param array     $data                       数据
     * @return int
     */

    public function insertAllContract($data) {
        $result = $this->db->insertAll($data);
        return $result;
    }

    /**
     * 分页查询合同
     * @author ligang
     * @param array $where
     * @param int $list
     * @param int $page
     * @param array $join
     * @param string $field
     * @param array $order
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\exception\DbException
     * @throws db\exception\DataNotFoundException
     * @throws db\exception\ModelNotFoundException
     * @date 2018/8/9 10:40
     */
    public function selectPageContract(array $where, int $list, int $page, array $join, string $field, array $order) {
        return $this->db->alias('a')->where($where)->join($join)->field($field)->order($order)->page($page, $list)->select();
    }

    /**
     *
     * @author ligang
     * @param array $where
     * @param array $join
     * @param string $field
     * @param array $order
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\exception\DbException
     * @throws db\exception\DataNotFoundException
     * @throws db\exception\ModelNotFoundException
     * @date 2018/8/9 11:04
     */
    public function selectContract(array $where, array $join, string $field, array $order) {
        return $this->db->alias('a')->where($where)->join($join)->field($field)->order($order)->select();
    }

    /**
     * 分页查询数据(不查询逻辑删除的数据)
     * @author ligang
     * @param array     $where                       AND查询条件
     * @param array     $whereOr                     OR查询条件
     * @return array
     * @return string|int    $data['currentPage']    获取当前页
     * @return string|int    $data['listRows']       每页显示数目
     * @return array         $data['data']           数据
     */
    public function selectPage($where = array(), $whereOr = array(), $order = 'is_Expire desc,is_Core desc,rq_contract.update_time desc,rq_contract.add_time desc') {
        //获取分页配置
        $currentPage = !empty($where['page']) ? $where['page'] : 1;
        unset($where['page']);
        $Configuration = new Configuration();
        $listRows = intval($Configuration->getkey('pagesize'));
        //时间
        $datetimeStart = intval(strtotime('1970-10-1'));
        $datetimeEnd = time() * 10;
        $datetimeStart_renew = intval(strtotime('1970-10-1'));
        $datetimeEnd_renew = time() * 10;
        if (!empty($where['datetimeStart'])) {
            $datetimeStart = intval(strtotime($where['datetimeStart']));
        }
        if (!empty($where['datetimeEnd'])) {
            $datetimeEnd = intval(strtotime($where['datetimeEnd'])) + 24 * 3600;
        }

        unset($where['datetimeStart']);
        unset($where['datetimeEnd']);
        unset($where['datetimeStart_renew']);
        unset($where['datetimeEnd_renew']);
        //-----------------------------
        //关联查询
        $join = [
            ['rq_customer', 'rq_customer.user_id = rq_contract.user_id'],
            ['rq_operation_info', 'rq_operation_info.o_id = rq_contract.operation_id'],
            ['rq_administrative_info', 'rq_administrative_info.a_id = rq_contract.administrative_id']
        ];
        //限制查询（只查询没有被逻辑删除的数据）
        $where['rq_contract.is_delete'] = 0;

        //获取数据
        $page = $this->db->join($join)
                        /* ->whereTime('rq_contract.installed_time','between',[$datetimeStart,$datetimeEnd]) */
                        ->where($where)->whereOr($whereOr)->order($order)
                        ->field('
            contract_id,
            username,
            is_Expire,
            is_Core,
            corporate_name,
            contract_no,
            rq_operation_info.company_name as operation_name,
            rq_administrative_info.company_name as administrative_name,
            id_card,
            for_core_time,
            for_core_cost,
            for_core_cycle,
            contract_type,
            installed_time,
            renew_date')
                        ->cache(true)->page($currentPage, $listRows)->select();
        $data = array();
        //计算数据总数
        $data['page']['count'] = $this->db->join($join)
                        ->whereTime('rq_contract.installed_time', 'between', [$datetimeStart, $datetimeEnd])
                        ->where($where)->whereOr($whereOr)->count();
        //获取当前页
        $data['page']['currentPage'] = $currentPage;
        //计算共有多少页
        $data['page']['lastPage'] = intval(ceil($data['page']['count'] / $listRows));
        ;
        //每页显示数目
        $data['page']['listRows'] = $listRows;
        //每页数据
        foreach ($page as $key => $value) {
            $page[$key]['installed_time'] = !empty($value['installed_time']) ?? date('Y/m/d', $value['installed_time']);
            $page[$key]['for_core_time'] = !empty($value['for_core_time']) ?? date('Y/m/d', $value['for_core_time']);
            if ($value['contract_type'] == 0) {
                $page[$key]['contract_type'] = "未升级VIP";
            } else {
                $page[$key]['contract_type'] = "已升级VIP";
            }
        }
        $data['data'] = $page;
        return $data;
    }

    /*
     *  合同
     *  @author liganmg
     *  @param  array   $where  条件
     *  @param  string  $field  查询字段
     *  @return array
     */

    public function selectData($where = [], $field = '*') {
        $result = $this->db->where($where)->field($field)->select();
        foreach ($result as $k => $v) {
            $repair_id = db('work_order')->where(['contract_id' => $result[$k]['contract_id']])->value('repair_id');
            $result[$k]['engineer'] = db('engineers')->where('engineers_id', $repair_id)->value('engineers_name');
        }
        return $result;
    }

    /*
     *  添加合同备注
     *  @author ligang
     *  @param  array   $data   添加的数据
     *  @return int
     */

    public function insertContractRemark($data) {
        $result = Db::name('contract_remark')->insertGetId($data);
        if ($result) {
            writelog($this->user_data['uid'], $this->user_data['username'], '用户【' . $this->user_data['username'] . '】新增成功：合同备注', 1, $this->db_name_log);
        } else {
            writelog($this->user_data['uid'], $this->user_data['username'], '用户【' . $this->user_data['username'] . '】新增失败：合同备注', 0, $this->db_name_log);
        }
        return $result;
    }

    /*
     *  修改合同备注
     *  @author ligang
     *  @param  array   $where  条件
     *  @param  array   $data   修改的数据（可包含主键）
     *  @return int
     */

    public function updateContractRemark($where = [], $data) {
        $result = Db::name('contract_remark')->where($where)->update($data);
        if ($result) {
            writelog($this->user_data['uid'], $this->user_data['username'], '用户【' . $this->user_data['username'] . '】修改成功：合同备注', 1, $this->db_name_log);
        } else {
            writelog($this->user_data['uid'], $this->user_data['username'], '用户【' . $this->user_data['username'] . '】修改失败：合同备注', 0, $this->db_name_log);
        }
        return $result;
    }

    /**
     *
     * @author ligang
     * @param array $where
     * @param array $join
     * @param string $field
     * @return array|false|\PDOStatement|string|Model
     * @throws \think\exception\DbException
     * @throws db\exception\DataNotFoundException
     * @throws db\exception\ModelNotFoundException
     * @date 2018/8/10 9:51
     */
    public function findJoinContract(array $where, array $join, $field = '*') {
        return $this->db->where($where)->join($join)->field($field)->find();
    }

    /**
     * 合同详情
     * @author ligang
     * @param   array $where    条件
     * @param   string $field   查询字段
     * @param   array $join     关联表数组
     * @return array
     */
    public function details($where, $join = [], $field = '*') {
        $result = empty($join) ? $this->db->alias('a')->where($where)->field($field)->find() : $this->db->alias('a')->where($where)->field($field)->join($join)->find();
//echo $this->db->alias('a')->getLastSql();die();
        //        $result = empty($join)?$this->db->where($where)->field($field)->find():$this->db->where($where)->field($field)->join($join)->find();
        return $result;
    }

    /**
     * 合同图片
     * @author ligang
     * @param array $where    条件
     * @param string $field    字段(多个字段以逗号分隔)
     * @return array
     */
    public function contractImg($where = [], $field = '*') {
        $result = $this->db->where($where)->field($field)->find();
        return $result;
    }

    /*
     *  获取合同设备的数量
     *  @author ligang
     *  @param  array   $where  条件
     *  @return int
     */

    public function getEquipmentNumber($where = []) {
        $num = $this->contract_equipment->where($where)->count();
        return $num;
    }

    /**
     * 合同设备关联查询
     * @author ligang
     * @param $where
     * @return array|bool
     */
    public function contractEquipment($where = [], $join = [], $field = '*') {
        if (empty($join)) {
            $equipment = $this->contract_equipment->alias('a')->where($where)->field($field)->select();
        } else {
            $equipment = $this->contract_equipment->alias('a')->where($where)->join($join)->field($field)->select();
        }
        return $equipment;
    }

    /*
     *  添加合同操作记录
     *  @author ligang
     *  @param array $data
     *  @return int
     */

    public function addContractLog($data = []) {
        $data['do_id'] = $this->user_data['uid'];
        $data['do_time'] = time();
        $result = Db::name('contract_log')->insertGetId($data);
        if ($result) {
            writelog($this->user_data['uid'], $this->user_data['username'], '用户【' . $this->user_data['username'] . '】添加成功：合同操作记录', 1, $this->db_name_log);
        } else {
            writelog($this->user_data['uid'], $this->user_data['username'], '用户【' . $this->user_data['username'] . '】添加失败：合同操作记录', 0, $this->db_name_log);
        }
        return $result;
    }

    /*
     *  系统自动添加合同操作记录
     *  @author ligang
     *  @param array $data(二维数组)
     *  @return int|bool
     */

    public function systemAddContractLog($data) {
        $result = Db::name('contract_log')->insertAll($data);
        $Log['admin_id'] = 0;
        $Log['admin_name'] = '【系统】';
        $Log['description'] = '【系统】批量生成合同操作记录';
        $Log['status'] = 1;
        $Log['ip'] = request()->ip();
        $Log['add_time'] = time();
        Db::name('admin_log')->insert($Log);
        return $result;
    }

    /*
     *  查询账号
     *  @author ligang
     *  @param  string  $db     数据表
     *  @param  array   $where  条件
     *  @param  string  $field  查询字段
     *  @return array
     */

    public function findUser($db, $where = [], $join = [], $field = '*') {
        if (empty($join)) {
            $result = Db::name($db)->where($where)->field($field)->find();
        } else {
            $result = Db::name($db)->where($where)->join($join)->field($field)->find();
        }

        return $result;
    }

    /*
     *  查询合同操作记录
     *  @author ligang
     *  @param array $where
     *  @param array $join        关联查询
     *  @param array $field       查询字段
     *  @param array $page        页数
     *  @param array $page_number 每页显示数目
     *  @return int
     */

    public function getContractLog($where = [], $join = [], $field = '*', $page = 1, $page_number = 5) {
        if (empty($join)) {
            $result = Db::name('contract_log')->where($where)->field($field)->page($page, $page_number)->order('do_time', 'desc')->select();
        } else {
            $result = Db::name('contract_log')->where($where)->join($join)->field($field)->page($page, $page_number)->order('do_time', 'desc')->select();
        }
        return $result;
    }

    /*
     *  更新设备信息
     *  @author ligang
     *  @param array $data  更新数据（包含主键）
     *  @return int
     */

    public function updateEquipments($data) {
        $result = Db::name('equipments')->update($data);
        if ($result) {
            writelog($this->user_data['uid'], $this->user_data['username'], '用户【' . $this->user_data['username'] . '】更新成功：更新设备→设备ID' . $data['equipments_id'] . '→' . $data['equipments_number'], 1, $this->db_name_log);
        } else {
            writelog($this->user_data['uid'], $this->user_data['username'], '用户【' . $this->user_data['username'] . '】更新失败：更新设备→设备ID' . $data['equipments_id'] . '→' . $data['equipments_number'], 0, $this->db_name_log);
        }
        return $result;
    }

    /*
     *  更新合同
     *  @author ligang
     *  @param array    $data   更新数据（包含主键）
     *  @param array    $where  条件
     *  @return int|bool
     */

    public function updateContract($where = [], $data) {
        $result = $this->db->where($where)->update($data);
        if ($result) {
            writelog($this->user_data['uid'], $this->user_data['username'], '用户【' . $this->user_data['username'] . '】更新成功：更新合同', 1, $this->db_name_log);
        } else {
            writelog($this->user_data['uid'], $this->user_data['username'], '用户【' . $this->user_data['username'] . '】更新失败：更新合同', 0, $this->db_name_log);
        }
        return $result;
    }

    /*
     *  添加设备备注
     *  @author ligang
     *  @param array $data
     *  @return int
     */

    public function addEquipmentsRemark($data) {
        $result = Db::name('equipments_remark')->insertGetId($data);
        if ($result) {
            writelog($this->user_data['uid'], $this->user_data['username'], '用户【' . $this->user_data['username'] . '】添加成功：设备备注→合同设备关联ID' . $data['contract_equipment_id'] . '→' . $data['equipments_remark'], 1, $this->db_name_log);
        } else {
            writelog($this->user_data['uid'], $this->user_data['username'], '用户【' . $this->user_data['username'] . '】添加失败：设备备注→合同设备关联ID' . $data['contract_equipment_id'] . '→' . $data['equipments_remark'], 0, $this->db_name_log);
        }
        return $result;
    }

    /*
     *  获取设备备注
     *  @author ligang
     *  @param array $where
     *  @return array|bool
     */

    public function equipmentsRemark($where = []) {
        $result = Db::name('equipments_remark')->where($where)->select();
        return $result;
    }

    /**
     *  设备记录
     * @author ligang
     * @param int $type     记录类型（1新装记录、2维修记录、3换芯纪录、4拆机记录、5移机记录、6续费记录、7换芯+维修记录、8续费+维修记录）
     * @param array $where  条件（AND）
     * @return array|bool
     */
    public function equipmentRecord($type, $where = []) {
        switch ($type) {
            case 1:
                //新装记录
                $New_Record = new NewRecord();
                $result = $New_Record->selectWhereAll($where);
                return $result;
                break;
            case 2:
                //维修记录
                $repair_record = new RepairRecord();
                $result = $repair_record->selectWhereAll($where);
                return $result;
                break;
            case 3:
                //换芯纪录
                $For_Core_Record = new ForCoreRecord();
                $result = $For_Core_Record->selectWhereAll($where);
                return $result;
                break;
            case 4:
                //拆机记录
                $Disassemble_Record = new DisassembleRecord();
                $result = $Disassemble_Record->selectWhereAll($where);
                return $result;
                break;
            case 5:
                //移机记录
                $Shift_Record = new ShiftRecord();
                $result = $Shift_Record->selectWhereAll($where);
                return $result;
                break;
            case 6:
                //续费记录
                $Renew_Record = new RenewRecord();
                $result = $Renew_Record->selectWhereAll($where);
                return $result;
                break;
            case 7:
                //换芯+维修记录
                $For_Core_Repair_Record = new ForCoreRepairRecord();
                $result = $For_Core_Repair_Record->selectWhereAll($where);
                return $result;
                break;
            case 8:
                //续费+维修记录
                $Renew_Repair_Record = new RenewRepairRecord();
                $result = $Renew_Repair_Record->selectWhereAll($where);
                return $result;
                break;
            default:
                return ['code' => 0, 'msg' => '请传入有效参数'];
        }
    }

    /**
     * 获取所有省级承包商数据
     * @author ligang
     * @return array|bool
     */
    public function selectOperationInfo() {
        $res = Db::name('operation_info')->field('o_id,company_name,province_name,province_id')->select();
        return $res;
    }

    /**
     * 获取所有行政中心数据
     * @author ligang
     * @param   array    $where    查询条件（一维数组）
     * @return array|bool
     */
    public function selectAdministrativeInfo($where = array()) {
        $res = Db::name('administrative_info')->where($where)->field('a_id,company_name,area_name,area_id')->select();
        return $res;
        exit();
        //对多行政区域的处理
        $data = array();
        foreach ($res as $key => $value) {
            if (strpos($value['area_name'], ',') != false) {
                $a_id = $value['a_id'];
                $company_name = $value['company_name'];
                $arr_area_name = explode(',', $value['area_name']);
                $arr_area_id = explode(',', $value['area_id']);
                foreach ($arr_area_name as $k => $v) {
                    $data[$k]['a_id'] = $a_id;
                    $data[$k]['company_name'] = $company_name;
                    $data[$k]['area_name'] = $v;
                    $data[$k]['area_id'] = $arr_area_id[$k];
                }
            } else {
                array_push($data, $value);
            }
        }
        //去除相同的区域
        $i = 0;
        foreach ($data as $kk => $vv) {
            if ($i + 1 < count($data)) {
                if (in_array($vv['a_id'], $data[$i + 1])) {
                    $i = 0;
                    array_splice($data, $kk, 1);
                } else {
                    $i++;
                }
            }
            continue;
        }
        return $data;
    }

    /*
     *  更新合同到期时间（系统操作）
     *  @author ligang
     *  @param array    $data   更新数据（包含主键）
     *  @param array    $where  条件
     *  @return int|bool
     */

    public function updateContractExpire($where = [], $data) {
        $result = $this->db->where($where)->update($data);
        if ($result != 0) {
            writelog(0, '系统', '【操作成功】系统更新合同到期时间', 1, $this->db_name_log);
        } else {
            writelog(0, '系统', '【操作失败】更新合同到期时间', 0, $this->db_name_log);
        }
        return $result;
    }

    /*
     *  添加合同操作记录（系统操作）
     *  @author ligang
     *  @param array $data
     *  @return int
     */

    public function addContractLogExpire($data = []) {
        $result = Db::name('contract_log')->insertGetId($data);
        if ($result) {
            writelog(0, '系统', '【操作成功】系统添加合同操作记录', 1, $this->db_name_log);
        } else {
            writelog(0, '系统', '【操作失败】系统添加合同操作记录', 0, $this->db_name_log);
        }
        return $result;
    }

    /**
     * @param $where
     * @return false|\PDOStatement|string|\think\Collection
     *        根据条件，查询所有合同信息
     */
    public function get_id_all($where, $field, $nowPage, $limits, $order = 'contract_id desc') {
        // 查询所有
        $data = $this->db
                ->field($field)
                ->where($where)
                ->page($nowPage, $limits)
                ->order($order)
                ->select();
        return $data;
    }

    /**
     * @param $where
     * @return int|string
     *        根据条件，获取合同数据数量
     */
    public function getCount($where) {
        // 查询数据数量
        $count = $this->db
                ->where($where)
                ->count();
        return $count;
    }

    /**
     * @param $where
     * @return int|string
     *        根据条件，获取合同绑定的设备数量
     */
    public function getEquipmentCount($where) {
        // 查询合同下设备
        $count = Db::name('contract_equipment')->where($where)->count();
        return $count;
    }

    /**
     * @param $where
     * @return false|\PDOStatement|string|\think\Collection
     *       根据合同id，获取合同设备信息
     */
    public function getEquipmentAll($where) {
        $data = Db::name('contract_equipment')->where($where)->select();
        return $data;
    }

    /**
     * @param $where
     * @return array|false|\PDOStatement|string|Model
     *      根据条件获取单条数据
     */
    public function getOne($where) {
        $data = $this->db->where($where)->find();
        return $data;
    }

    // 连表查询列表
    public function getJoinAll($where = [], $join, $nowPage, $pageSize, $field = '*', $order = 'add_time desc') {
        //获取数据
        $page = $this->db->alias('a')
                ->join($join)
                ->where($where)
                ->order($order)
                ->field($field)
                ->page($nowPage, $pageSize)
                ->select();
        $data = array();
        // 计算数据总数
        $data['page']['count'] = $this->db->alias('a')->join($join)->where($where)->count();
        // 获取当前页
        $data['page']['currentPage'] = $nowPage;
        // 计算共有多少页
        $data['page']['lastPage'] = intval(ceil($data['page']['count'] / $pageSize));
        ;
        // 每页显示数目
        $data['page']['listRows'] = $pageSize;
        foreach ($page as $key => $value) {
            $page[$key]['installed_time'] = empty($value['installed_time']) ? '' : date('Y/m/d', $value['installed_time']);
            $page[$key]['exire_date_date'] = empty($value['exire_date']) ? '' : date('Y/m/d', $value['exire_date']);
            $page[$key]['package_mode'] = empty($value['package_mode']) ? '' : config('working_mode')[$value['package_mode']];
            $page[$key]['status_name'] = config('contract_status')[$value['status']];
            $page[$key]['warn'] = false;
            if ($value['status'] == 4 && $value['exire_date'] - time() < 15 * 86400) {
                $page[$key]['warn'] = true;
            }
        }
        $data['data'] = $page;
        return $data;
    }

    // 添加操作
    public function add($data=[])
    {
        $result = Db::name('Contract')->insertGetId($data);
        return $result;
    }




}
